<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <link rel="stylesheet" href="css/page-common.css">
    <link rel="stylesheet" type="text/css" href="http://www.jq22.com/jquery/font-awesome.4.6.0.css">
    <link rel="stylesheet" href="css/upload.css"/>
    <title></title>
    <style>
        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        html{
            height: 100%;
        }
        body{
            background: skyblue;
        }
        body{
            height: 100%;
            position: relative;
        }

    </style>
</head>
<body>

<button id='fileChooseButton' class="button blue rarrow file-input-mask">加载图片</button>
<img id="previewResult" />
<img id="needCropImg" style="display:none" />
<div class="app" id="uploadPage">
    <div class="upload-loading">
        <span class="centerXY"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i></span>
    </div>
    <div class="bar"><a class="back pull-left" id="closeCrop"><i class="fa fa-reply"></i></a><a id="getFile" class="pull-right">使用</a></div>
    <div class="main">
        <canvas class="upload-mask">

        </canvas>
        <div class="preview-box">
            <img id="preview"/>
        </div>
        <canvas class="photo-canvas">

        </canvas>
        <a  id="rotateBtn">
            <i class="fa fa-rotate-right  fa-3x"></i>
            <div>旋转照片</div>
        </a>
    </div>
</div>
</body>
<script src="js/require.js" ></script>
<script src="js/main.js"></script>
<script src="js/canvas-toBlob.js"></script>
<script>
    var myCrop;
    //防require缓存
    require.config({
        urlArgs:"bust="+new Date
    })
    require(["jquery",'hammer','tomPlugin',"tomLib",'hammer.fake','hammer.showtouch'],function($,hammer,plugin,T){
        document.addEventListener("touchmove",function(e){
            e.preventDefault();
        })
        //初始化图片大小300*300
        var opts={cropWidth:300,cropHeight:300},
                $file=$("#file"),
                previewStyle={x:0,y:0,scale:1,rotate:0,ratio:1},
                transform= T.prefixStyle("transform"),
                $previewResult=$("#previewResult"),
                $previewBox=$(".preview-box"),
                $rotateBtn=$("#rotateBtn"),
                $getFile=$("#getFile"),
                $preview=$("#preview"),
                $uploadPage=$("#uploadPage"),
                $mask=$(".upload-mask"),
                $loading=$(".upload-loading"),
                maskCtx=$mask[0].getContext("2d"),
                $needCropImg=$("#needCropImg");

        //这是插件调用主体
        myCrop=T.cropImage({
//            bindFile:$file,//绑定Input file
            bindFile:$needCropImg[0],//绑定一个图片
            enableRatio:true,//是否启用高清,高清得到的图片会比较大
            canvas:$(".photo-canvas")[0],  //放一个canvas对象
            cropWidth:opts.cropWidth,       //剪切大小
            cropHeight:opts.cropHeight,
            bindPreview:$preview,      //绑定一个预览的img标签
            useHammer:true,            //是否使用hammer手势，否的话将不支持缩放
            oninit:function(){

            },
            onChange:function(){
                $loading.show();
                resetUserOpts();
            },
            onLoad:function(data){
                //用户每次选择图片后执行回调
                previewStyle.ratio=data.ratio;
                $preview.attr("src",data.originSrc).css({width:data.width,height:data.height}).css(transform,'scale('+1/previewStyle.ratio+')');
                myCrop.setCropStyle(previewStyle)
                $loading.hide();
            }
        });
        function resetUserOpts(){
            $(".photo-canvas").hammer('reset');
            previewStyle={scale:1,x:0,y:0,rotate:0};
            $previewResult.attr("src",'').hide();
            $preview.attr("src",'')
        }
        $('#fileChooseButton').on('click',function(){
            resetUserOpts();
            //单独绑定图片时用到
            //只是为了演示，需要你来放一个真实的图片地址
            $needCropImg[0].src='./img/9-1.jpg?'+Math.random();
        })
        $(".photo-canvas").hammer({
            gestureCb:function(o){
                //每次缩放拖拽的回调
                $.extend(previewStyle,o);
                console.log("用户修改图片",previewStyle)
                $preview.css(transform,"translate3d("+ previewStyle.x+'px,'+ previewStyle.y+"px,0) rotate("+previewStyle.rotate+"deg) scale("+(previewStyle.scale/previewStyle.ratio)+")")
            }
        })
        //选择图片
        $rotateBtn.on("click",function(){
            previewStyle.rotate+=90;
            if(previewStyle.rotate>=360){
                previewStyle.rotate-=360;
            }
            $(".photo-canvas").hammer('setRotate',previewStyle.rotate)
            myCrop.setCropStyle(previewStyle)
            $preview.css(transform,"translate3d("+ previewStyle.x+'px,'+ previewStyle.y+"px,0) rotate("+previewStyle.rotate+"deg) scale("+(previewStyle.scale/previewStyle.ratio)+")")
        })
        //获取图片并关闭弹窗返回到表单界面
        $getFile.on("click",function(){
            var cropInfo;
            $uploadPage.hide();
            myCrop.setCropStyle(previewStyle)
            //自定义getCropFile({type:"png",background:"red",lowDpi:true})
            cropInfo=myCrop.getCropFile({});
            $previewResult.attr("src",cropInfo.src).show();

            //可选传base64或者file对象
            //cropInfo.src cropInfo.dfd

            //you can upload img base64  :cheers:)
            console.info('拿到Base64了,传给后台吧？')//src.substr(22)
       /*     $.ajax({
                url:'http://127.0.0.1/testAdjustImg/upload.php',
                type:"post",
                dataType:"json",
                data:{base64:cropInfo.src.substr(22),uploadType:'base64'},//后端无需在过滤头
                success:function(data){
                    if(data.result==1){
                        console.log(data.imgPath)
                    }
                }
            })*/
            //you can upload new img file :cheers:)
            cropInfo.dfd.done(function(blob){
                if(blob){
                    var formData=new FormData;
                    blob.name='imgFile'
                    formData.append("imgFile",blob)
                    formData.append("uploadType",'imgFile');
                    $.ajax({
                        url:'http://127.0.0.1/testAdjustImg/upload.php',
                        type:"post",
                        data:formData,
                        processData:false,
                        contentType: false,
                        dataType:"json",
                        success:function(data){
                            console.log(data)
                            if(data.result==1){
                                console.log(data.imgPath)
                            }
                        }
                    })
                }
            })

        })
        //上传文件按钮&&关闭弹窗按钮
        $(document).delegate("#file","click",function(){
            $uploadPage.show();
        }).delegate("#closeCrop","click",function(){
            $uploadPage.hide();
            resetUserOpts();
            myCrop.setCropStyle(previewStyle)
        })
        $file.one("click",showCropModal)

        function showCropModal(){
            $uploadPage.show();
            $mask.prop({width:$mask.width(),height:$mask.height()})
            maskCtx.fillStyle="rgba(0,0,0,0.7)";
            maskCtx.fillRect(0,0,$mask.width(),$mask.height());
            maskCtx.fill();
            maskCtx.clearRect(($mask.width()-opts.cropWidth)/2,($mask.height()-opts.cropHeight)/2,opts.cropWidth,opts.cropHeight)
        }

        $needCropImg[0].addEventListener("load",showCropModal)

    })
</script>
</html>